﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Titan;
using StockMatch.Service.Entity;

namespace StockMatch.Service
{
    public class DayWinProjectService : ContextBoundObject
    {


        #region 增删改
        //提交方案
        public bool Insert(DayWinProject dayWinProject)
        {
            using (var cn = Environment.OpenSession())
            {
                try
                {
                    cn.BeginTransaction();
                    int i = cn.Insert(dayWinProject);
                    
                    User user = ServiceManager.UserService.GetUser(dayWinProject.UserId);
                    user.LockAmount += (dayWinProject.RiskMargin + dayWinProject.ManageMoney); //冻结金额
                    user.BalanceAmount -= user.LockAmount; //账户余额
                    bool a = ServiceManager.UserService.Update(user, User_.LockAmount, User_.BalanceAmount);

                    if (i > 0 && a)
                    {
                        cn.Commit();                    
                        dayWinProject.ProjectNumber = string.Format("S{0}", dayWinProject.ProjectId);
                        bool c = Update(dayWinProject, DayWinProject_.ProjectNumber);
                        return true;
                    }
                    cn.Rollback();
                    return false;
                }
                catch (Exception ex)
                {
                    cn.Rollback();
                    throw new StockException(ex.Message);
                }
            }
        }

        //开户
        public bool OpenAccount(int projectId,string tradingAccount, string tradingPassword)
        {
            DayWinProject dayWinProject = new DayWinProject
            {
                ProjectId = projectId
            };
            using (var cn = Environment.OpenSession())
            {
                if (!cn.Select(dayWinProject, DayWinProject_.ALL,DayWinProject_.User.ALL))
                {
                    return false;
                }
            }

            dayWinProject.TradingAccount = tradingAccount;
            dayWinProject.TradingPassword = tradingPassword;
            dayWinProject.ProjectState = (int)ProjectStateEnum.Trading;//操盘中的状态

            using (var cn = Environment.OpenSession())
            {
                cn.BeginTransaction();
                try
                {
                   bool a= cn.Update(dayWinProject, DayWinProject_.ProjectState, DayWinProject_.TradingAccount,
                        DayWinProject_.TradingPassword) > 0;

                   User user = dayWinProject.User;
                   user.LockAmount -= (dayWinProject.RiskMargin + dayWinProject.ManageMoney); //锁定金额
                   user.RiskAmount += dayWinProject.RiskMargin; //风险保证金
                   user.ManagAmount += dayWinProject.ManageMoney; //管理费
                   user.StockAmount += dayWinProject.FirmCapital;//配资金额
                   bool b = cn.Update(user,User_.LockAmount,User_.RiskAmount,User_.ManagAmount,User_.StockAmount) > 0;

                   //支付账号管理费
                   DayWinProjectAccount projectAccount = new DayWinProjectAccount();
                   projectAccount.ProjectId = dayWinProject.ProjectId;
                   projectAccount.PayMoney = dayWinProject.ManageMoney;
                   projectAccount.PayState = 1;
                   projectAccount.PayTime = DateTime.Now;
                   bool c = cn.Insert(projectAccount) > 0;

                    if (a && b && c)
                    {
                        cn.Commit();
                        return true;
                    }
                    else
                    {
                        cn.Rollback();
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    cn.Rollback();
                    throw new Exception(ex.Message);
                }  
            }
        }

        //追加保证金
        public int AddRiskMargin(int projectId,int riskMargin,int type)
        {
            #region 查询当天是否已超过追加次数
            using (IDbSession cn = Environment.OpenSession())
            {
                object obj =
                    cn.ExecuteScalar(
                        "select count(*) from daywinprojectriskmargin where date(addtime) = curdate() and ProjectId=" +
                        projectId);
                if (obj != null && (int)obj>=5)
                {
                    return 2;
                }
            }
            #endregion

            using (var cn = Environment.OpenSession())
            {
                DayWinProjectRiskMargin dayWinProjectRiskMargin = new DayWinProjectRiskMargin
                {
                    ProjectId = projectId,
                    AddMoney = riskMargin,
                    AddState = 1,
                    AddTime = DateTime.Now,
                    Type = type,
                };
                return cn.Insert(dayWinProjectRiskMargin);
            }
        }

        //提取保证金

        //终止操盘

        //账号管理费
        

        public bool Update(DayWinProject dayWinProject,params object[] updateProperty)
        {
            try
            {
                using (var cn = Environment.OpenSession())
                {
                    return cn.Update(dayWinProject, updateProperty) > 0;
                }
            }
            catch (Exception ex)
            {
                throw new StockException(ex);
            }
        }

        public bool Delete(int id)
        {
            DayWinProject dayWinProject = new DayWinProject()
            {

            };
            try
            {
                using (var cn=Environment.OpenSession())
                {
                    return cn.Delete(dayWinProject) > 0;
                }
            }
            catch (Exception ex)
            {
                throw new StockException(ex.Message);
            }
        }

        #endregion

        #region 查询

        public DayWinProject GetDayWinProject(int id)
        {
            DayWinProject dayWinProject = new DayWinProject()
            {
                ProjectId = id
            };
            try
            {
                using (var cn = Environment.OpenSession())
                {
                    if (!cn.Select(dayWinProject))
                    {
                        return null;
                    }
                    return dayWinProject;
                }
            }
            catch (Exception ex)
            {
                throw new StockException(ex.Message);
            }
        }


        public DayWinProjects GetDayWinProjects(QueryExpression query)
        {
            try
            {
                using (var cn = Environment.OpenSession())
                {
                    DayWinProjects dayWinProjects = new DayWinProjects();
                    dayWinProjects.TotalCount = cn.SelectCollection(dayWinProjects.Items, query);
                    return dayWinProjects;
                }
            }
            catch (Exception ex)
            {
                throw new StockException(ex.Message);
            }
        }

        #endregion

    }
}
